<template>
  <el-form-item label="应用对象：" prop="DeviceObjType">
    <el-radio :input-attrs="{ 'aria-hidden': 'false' }" v-model="localForm.DeviceObjType"
      @change="handleDeviceObjTypeChange" :label="1">全部</el-radio>
    <el-radio :input-attrs="{ 'aria-hidden': 'false' }" v-model="localForm.DeviceObjType"
      @change="handleDeviceObjTypeChange" :label="2">指定部门</el-radio>
    <el-radio :input-attrs="{ 'aria-hidden': 'false' }" v-model="localForm.DeviceObjType"
      @change="handleDeviceObjTypeChange" :label="8">指定角色</el-radio>
    <el-radio :input-attrs="{ 'aria-hidden': 'false' }" v-model="localForm.DeviceObjType"
      @change="handleDeviceObjTypeChange" :label="6">指定资产</el-radio>

    <el-cascader v-if="localForm.DeviceObjType === 2" :disabled="localForm.DeviceObjType === 1" multiple
      style="width:100%;" :placeholder="placeholderText" ref="cascaderAddr" v-model="localForm.DeviceObj" clearable
      :options="deviceObjList" :props="{
        children: 'Children',
        expandTrigger: 'hover',
        label: 'Name',
        value: 'ID',
        emitPath: false,
        multiple: true,
        checkStrictly: true
      }" />

    <el-select v-if="localForm.DeviceObjType === 8" style="width:100%" v-model="localForm.DeviceObj" multiple
      placeholder="请选择角色">
      <el-option v-for="(item, index) in roleList" :key="index" :label="item.Role" :value="item.Role" />
    </el-select>

    <el-cascader v-if="localForm.DeviceObjType === 6" style="width:100%;" placeholder="请选择资产" ref="cascaderAddr"
      v-model="localForm.DeviceObj" :options="deviceObjList" :props="cascaderProps" />
  </el-form-item>
</template>

<script>
import { connrequest } from '@/api/firstPage'
import { transformToCascaderTree } from "@/utils/index.js";

export default {
  name: 'DeviceObjectSelector',
  props: {
    form: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      deviceObjList: [],
      roleList: [],
      cascaderProps: {
        children: 'Children',
        expandTrigger: 'hover',
        label: 'Name',
        value: 'ID',
        emitPath: false,
        multiple: true,
        checkStrictly: false
      }
    }
  },
  computed: {
    localForm: {
      get() {
        if (this.form.DeviceObjType === 2) {
          this.GetDepartmentDeviceSumTree()
        } else if (this.form.DeviceObjType === 8) {
          this.getRoleStatus()
        } else if (this.form.DeviceObjType === 6) {
          this.initData()
        }
        return this.form
      },
      set(val) {
        this.$emit('update:form', val)
      }
    },
    placeholderText() {
      if (this.localForm.DeviceObjType === 1) return '全部'
      if (this.localForm.DeviceObjType === 2) return '请选择部门'
      return '请选择资产'
    }
  },
  methods: {
    async handleDeviceObjTypeChange(value) {
      this.$set(this.localForm, 'DeviceObj', '')
      if (value === 2 ) {
        await this.GetDepartmentDeviceSumTree()
      } else if (value === 8) {
        await this.getRoleStatus()
      } else if (value === 6) {
        await this.initData()
      }
    },
    async GetDepartmentDeviceSumTree() {
      const res = await connrequest('GetDepartmentDeviceSumTree')
      const deviceObjList = transformToCascaderTree(res.Data.Department)
      this.deviceObjList = deviceObjList
    },

    async getRoleStatus() {
      const res = await connrequest('GetParamDictRole')
      this.roleList = res.Data
    },
    async initData(searchobj = {}) {
      try {
        // 获取部门数据
        const deptResponse = await connrequest('GetDepartmentDeviceSumTree')
        const departments = deptResponse.Data.Department
        // 获取所有设备数据
        const data = {
          Paging: {
            QueryPageNo: 1,
            QueryPageLength: 100000
          }
        }
        const deviceResponse = await connrequest('GetDevice', data) // 你需要确认是否有这个接口
        const devices = deviceResponse.Data
        // 生成树结构
        this.deviceObjList = this.initDeviceTree(departments, devices)
      } catch (error) {
        console.error('初始化数据失败:', error)
      }
    },
    // 将设备数据转换为 el-cascader 树结构的函数
    initDeviceTree(departments, devices) {
      let deviceObjList = []
      // 创建部门映射表
      const departmentMap = new Map();
      const departmentClones = departments.map(dept => ({
        ...dept,
        Children: []
      }));
      // 建立父子关系
      departmentClones.forEach(dept => {
        departmentMap.set(dept.ID, dept);
        if (dept.ParentID === 0) {
          deviceObjList.push(dept);
        } else {
          const parent = departmentMap.get(dept.ParentID);
          parent && parent.Children.push(dept);
        }
      });
      // 将设备挂载到对应部门
      devices.forEach(device => {
        const dept = departmentMap.get(device.DepartmentID);
        if (dept) {
          dept.Children.push({
            ...device,
            ID: device.DeviceUUID,
            Name: device.DeviceName || device.DeviceCode || '未命名设备',
            Children: null,
            leaf: false,
            isDevice: true
          });
        }
      });
      // 递归过滤空部门
      const filterEmptyDepartments = (nodes) => {
        return nodes.filter(node => {
          // 保留设备节点
          if (node.isDevice) return true;
          // 递归过滤子节点
          if (node.Children) {
            node.Children = filterEmptyDepartments(node.Children);
          }
          // 保留有子节点（部门或设备）的部门
          return node.Children && node.Children.length > 0;
        });
      };
      deviceObjList = filterEmptyDepartments(deviceObjList)
      return deviceObjList
    }
  }
}
</script>